<?php

namespace app\store\controller\appointment;

use app\common\model\AppointmentRecord;
use app\store\controller\Controller;
use app\store\model\appointment\Order as OrderModel;
use app\store\model\appointment\Service;
use app\store\model\appointment\Time as TimeModel;
use app\store\model\appointment\Type as TypeModel;
use app\common\enum\AppointmentStatus;
use app\common\service\Order as OrderService;
use app\store\model\server\User as UserModel;
use app\store\model\OrderGoods;
use think\Db;
/**
 * 预约订单
 * Class Grade
 * @package app\store\controller\appointment
 */
class Order extends Controller
{
    /**
     * 添加等级
     * @return array|bool|mixed
     * @throws \Exception
     */
    public function add()
    {
        $model = new OrderModel;
        if (!$this->request->isAjax()) {
            $order_id = OrderService::createOrderNo();

            $userModel = new UserModel;
            $service_list = $userModel->getList();

            $status_list = AppointmentStatus::data();

            $timeModel = new TimeModel;
            $time_list = $timeModel->getList();

            $typeModel = new TypeModel;
            $type_list = $typeModel->getList();

            return $this->fetch('add',
                array_merge(compact('order_id', 'status_list', 'service_list', 'time_list', 'type_list')));
        }
        // 新增记录
        $data = $this->postData('model');
        if ($model->add($this->postData('model'))) {
            $order_id = $model->getLastInsID();
            $appointment_date = strtotime($data['appointment_date']);
            $lastorder = Db::name("appointment_order")->where(array("service_id"=>$data['service_id'],"type_id"=>$data['type_id'],"appointment_date"=>$appointment_date))->order(['order_target'=>'desc'])->find();
            if($lastorder && $lastorder['order_target']>0){
                $order_target = $lastorder['order_target']+1;
            }else{
                $order_target = 1;
            }
            Db::name("appointment_order")->where(array("id"=>$order_id))->update(['order_target'=>$order_target]);

            return $this->renderSuccess('添加成功', url('appointment/all_list'));
        }
        return $this->renderError($model->getError() ?: '添加失败');
    }

    /**
     * 预约编辑
     * @return array|bool|mixed
     */
    public function edit()
    {
        $order_id = input('order_id');
        // 订单列表
        $model = new OrderModel;

        if (!$this->request->isAjax()) {
            // 商品详情
            $model = $model->where('order_id', $order_id)->find();
            $data = [
                'type_id' => $model['type_id'],
                'date_id' => date("Y-m-d", $model['appointment_date']),
                'time_id' => $model['time_id'],
                'order_id' => $model['id'],
            ];

            $service_list = $model->getServerMan($data);

            $model['time_id'] = explode(',',$model['time_id']);

            $status_list = AppointmentStatus::data();

            $serviceModel = new Service;
            $service_info = $serviceModel->where('order_id', $model['id'])->find();

            $timeModel = new TimeModel;
            $time_list = $timeModel->getList(['type_id' => $model['type_id']]);


            foreach($time_list as $k=>$v){
                $orders = Db::name("appointment_order")->where('find_in_set(:time_id,time_id)',['time_id'=>$v['time_id']])->where(array('service_id'=>$model['service_id'],'appointment_date'=>$model['appointment_date']))->select()->toArray();
                $str = "";
                foreach($orders as $key=>$val){
                    if($val['order_target'] >0){
                        $str .= $val['order_target'].",";
                    }
                }
                $time_list[$k]['target'] = $str;
            }

            $typeModel = new TypeModel;
            $type_list = $typeModel->getListType($model['type_id']);

            $orderGoodsModel = new OrderGoods;
            $order_goods_list = $orderGoodsModel->getOrderGoods($model['user_order_id']);

            if ($model['user_order_id'] > 0) {
                $order = Db("order")->where('order_id', $model['user_order_id'])->field('order_no,total_price')->find();
                $model['user_order_name'] = $order['order_no'] . '/' . $order['total_price'];
            } else {
                $model['user_order_name'] = '';
            }

            return $this->fetch(
                'edit',
                array_merge(compact('status_list', 'service_list', 'model', 'time_list', 'type_list', 'order_goods_list', 'service_info'))
            );
        }

        $data = $this->postData('model');
        $service_id = $data['service_id'];
        $order = Db::name("appointment_order")->where(array("order_id"=>$order_id))->find();


        // 更新记录
        if ($model->edit($this->postData('model'))) {
            //YPP 改变服务人员
            if($order['service_id'] != $service_id){
                Db::name("appointment_order")->where(array("order_id"=>$order_id))->update(['service_status'=>1]);
                Db::name("appointment_service")->where(array("order_id"=>$order['id']))->update(['is_start'=>0,'start_time'=>0]);
                //$today = strtotime(date("Y-m-d",time()));
                $appointment_date = strtotime($data['appointment_date']);
                $lastorder = Db::name("appointment_order")->where(array("service_id"=>$data['service_id'],"type_id"=>$data['type_id'],"appointment_date"=>$appointment_date))->order(['order_target' => 'desc'])->find();
                if($lastorder && $lastorder['order_target']>0){
                    $order_target = $lastorder['order_target']+1;
                }else{
                    $order_target = 1;
                }
                Db::name("appointment_order")->where(array("order_id"=>$order_id))->update(['order_target'=>$order_target]);

            }
            return $this->renderSuccess('更新成功', url('appointment/all_list'));
        }
        return $this->renderError($model->getError() ?: '更新失败');
    }

    /**
     * 订单导出
     * @param string $dataType
     * @throws \think\exception\DbException
     */
    public function export($dataType)
    {
        return $this->model->exportList($dataType, $this->request->param());
    }

    public function orderRecord($order_id)
    {

        $list = AppointmentRecord::all(['order_id'=>$order_id]);

        $list = collection($list)->toArray();
        return json(['list'=>$list]);
    }

    public function get_time_list(){
        $type_id = input('type_id',1);
        $server = input('server');
        $datetime = strtotime(input('date'));
        $timeModel = new TimeModel;
        $time_list = $timeModel->getList(['type_id' => $type_id])->toArray();
        foreach($time_list as $k=>$v){
            $orders = Db::name("appointment_order")->where('find_in_set(:time_id,time_id)',['time_id'=>$v['time_id']])->where(array('service_id'=>$server,'appointment_date'=>$datetime))->select()->toArray();
            $str = "";
            foreach($orders as $key=>$val){
                if($val['order_target'] >0){
                    $str .= $val['order_target'].",";
                }
            }
            $time_list[$k]['target'] = $str;
        }

        return json($time_list);
    }

}